package Frame

import (
    "Dry/Constant"
    "fmt"
    "github.com/gin-gonic/gin"
    "reflect"
    "strings"
)

var ControllerList = new(AutoController)

type AutoController struct {
    List []interface{}
}

func (i *AutoController) Add(item interface{}) {
    i.List = append(i.List, item)
}

func (i *AutoController) GetList() []interface{} {
    return i.List
}

func RegisterRouter(r *gin.Engine) {
    list := ControllerList.GetList()
    for _, v := range list {
        tt := reflect.TypeOf(v)
        vv := reflect.ValueOf(v)
        temp := strings.Replace(tt.String(), "*", "", -1)
        data := strings.Split(temp, "Controller.")
        for i := 0; i < tt.NumMethod(); i++ {
            name := tt.Method(i).Name
            var method string
            var nameTemp string
            if strings.HasSuffix(name, "WithGet") {
                method = Constant.HTTP_REQUEST_GET
                nameTemp = strings.Replace(name, "WithGet", "", -1)
            } else if strings.HasSuffix(name, "WithPost") {
                method = Constant.HTTP_REQUEST_POST
                nameTemp = strings.Replace(name, "WithPost", "", -1)
            } else {
                continue
            }
            url := fmt.Sprintf("/%s/%s/%s", data[0], data[1], nameTemp)
            if method == Constant.HTTP_REQUEST_GET {
                r.GET(url, func(c *gin.Context) {
                    vv.MethodByName(name).Call([]reflect.Value{reflect.ValueOf(c)})
                })
            } else if method == Constant.HTTP_REQUEST_POST {
                r.POST(url, func(c *gin.Context) {
                    vv.MethodByName(name).Call([]reflect.Value{reflect.ValueOf(c)})
                })
            }
        }
    }
}
